package com.kuaifawu.lwnlawyerclient.Activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;


/**
 * Created by wyk123 on 2015/4/20.
 */
public class LWNSignatureActivity extends Activity implements View.OnClickListener{
    @ViewInject(R.id.save_buttonView)
    private ImageButton save_buttonView;
//    @ViewInject(R.id.centren_title)
//    private ImageButton centren_title;//区别是编辑签名还是介绍
    @ViewInject(R.id.editt_content_data)
    private EditText editt_content_data;
    @ViewInject(R.id.signature_back)
    private ImageButton signature_back;
//    @ViewInject(R.id.max_num)
//    private TextView max_num;

    private int index=-1;

    private String saveUrl="";
    private LWNSignatureActivity activity;
    private String content="";
    private int maxNum=-1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_singture);
        Bundle bundle=getIntent().getExtras();
        index=bundle.getInt("index");
        content=bundle.getString("content");
        initview();
    }


    private void initview(){

        ViewUtils.inject(this);
        activity=this;
        save_buttonView.setOnClickListener(this);
        signature_back.setOnClickListener(this);

//        if(index==1){
//            signature_back.setImageResource(R.drawable.individual_signature_title);
//
//            maxNum=24;
//            max_num.setText(maxNum+"");
//        }else if(index==2){
//            signature_back.setImageResource(R.drawable.personal_profile_title);
//            maxNum=800;
//            max_num.setText(maxNum+"");
//        }
        editt_content_data.setText(content);
        editt_content_data.setSelection(content.length());


        //editt_content_data.addTextChangedListener(mTextWatcher);
        //setLeftCount();

    }
//    private TextWatcher mTextWatcher=new TextWatcher() {
//        private CharSequence temp;
//        private int selectionStart;
//        private int selectionEnd;
//        @Override
//        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//        }
//
//        @Override
//        public void onTextChanged(CharSequence s, int start, int before, int count) {
//            temp=s;
//
//        }
//
//        @Override
//        public void afterTextChanged(Editable s) {
//            long number = maxNum - calculateLength(s);
//            max_num.setText("" + number);
//            selectionStart = editt_content_data.getSelectionStart();
//            selectionEnd = editt_content_data.getSelectionEnd();
//
//            if (calculateLength(s) > maxNum) {
//                editt_content_data.removeTextChangedListener(mTextWatcher);
//                Toast.makeText(LWNSignatureActivity.this,"最多可以输入"+maxNum+"个字哦！",Toast.LENGTH_SHORT).show();
//            while (calculateLength(s) > maxNum){
//                s.delete(selectionStart - 1, selectionEnd);
//                selectionStart--;
//                selectionEnd--;
//            }
//                max_num.setText("" + number);
//                editt_content_data.setSelection(s.length());//设置光标在最后
//                editt_content_data.addTextChangedListener(mTextWatcher);
//                setLeftCount();
//            }
//
////            if (temp.length() > maxNum) {
////                s.delete(selectionStart - 1, selectionEnd);
////                int tempSelection = selectionEnd;
////                editt_content_data.setText(s);
////                editt_content_data.setSelection(s.length());//设置光标在最后
////                Toast.makeText(LWNSignatureActivity.this,"最多可以输入"+maxNum+"个字哦！",Toast.LENGTH_SHORT).show();
////
////
////            }
//
//
//
//
//
//        }
//    };
    private long calculateLength(CharSequence c) {
        double len = 0;
        for (int i = 0; i < c.length(); i++) {
            int tmp = (int) c.charAt(i);
            if (tmp > 0 && tmp < 127) {
                len += 0.5;
            } else {
                len++;
            }
        }
        return Math.round(len);
    }

    /**
     * 刷新剩余输入字数
     */
//    private void setLeftCount() {
//        max_num.setText(String.valueOf((maxNum - getInputCount())));
//    }

    /**
     * 获取用户输入的分享内容字数
     *
     * @return
     */
//    private long getInputCount() {
//        return calculateLength(editt_content_data.getText().toString());
//    }



    @Override
    public void onClick(View v) {

        switch (v.getId()){
        case R.id.save_buttonView://保存
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(save_buttonView.getWindowToken(), 0);
            LWNNetworkCenter center=LWNNetworkCenter.getInstance();
            String saveData=editt_content_data.getText().toString();
            if(saveData.equals(content)){//没有做任何更改
                //Toast.makeText(LWNSignatureActivity.this,"您没有做任何更改哦",Toast.LENGTH_SHORT).show();
                ToastView_custom toast = new ToastView_custom(activity);
                toast.showCustom(activity, "您没有做任何更改哦");
                return;
            }else if(saveData.equals("")||saveData.length()==0){//没有输入任何内容
              //  Toast.makeText(LWNSignatureActivity.this,"请先输入内容！",Toast.LENGTH_SHORT).show();
                ToastView_custom toast = new ToastView_custom(activity);
                toast.showCustom(activity, "请先输入内容！");
               return;
            }
            RequestParams params=null;
            if(index==1){
                saveUrl=center.LWNBaseUrl_POST + "updatelawysignatu";
                params=center.getSavesigntrue(this,saveData,"signatu");

            }else if(index==2){
                saveUrl=center.LWNBaseUrl_POST + "updatelawyintro";
                params=center.getSavesigntrue(this,saveData,"intro");
            }
            saveDataToServer(saveUrl,center,params);

            break;
            case R.id.signature_back:
                InputMethodManager inputmanger1 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputmanger1.hideSoftInputFromWindow(signature_back.getWindowToken(), 0);
                finish();
                break;

        }
    }

    /**
     * 向服务器提交编辑的内容
     * @param url
     * @param center
     * @param params
     */
    private void saveDataToServer(String url,LWNNetworkCenter center,RequestParams params){
        final ProgressDialog proDialog = android.app.ProgressDialog.show(activity, "", getResources().getString(R.string.toast_send));
       HttpUtils http=center.getUtils();
        http.configDefaultHttpCacheExpiry(0*0);
       http.send(HttpRequest.HttpMethod.POST,url,params,new RequestCallBack<Object>() {
           @Override
           public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
               try{
                   JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                   String string_code = jsonObject.getString("code");
                   String string_msg = jsonObject.getString("msg");

                   //System.out.println(jsonObject);
//                   Toast toast = Toast.makeText(activity.getApplicationContext(),
//                           string_msg, Toast.LENGTH_SHORT);
//                   toast.setGravity(Gravity.CENTER, 0, 0);
//                   LinearLayout toastView = (LinearLayout) toast.getView();
//                   ImageView imageCodeProject = new ImageView(activity.getApplicationContext());
                   ToastView_custom toast = new ToastView_custom(activity);
       switch (Integer.parseInt(string_code)) {
            case 10000:
                proDialog.dismiss();
//             imageCodeProject.setImageResource(R.drawable.success);
//             toastView.addView(imageCodeProject, 0);
//             toast.show();
                toast.showCustom(activity, string_msg);
             finish();
                break;
           case 10002:
               proDialog.dismiss();
//               imageCodeProject.setImageResource(R.drawable.success);
//               toastView.addView(imageCodeProject, 0);
//               toast.show();
               toast.showCustom(activity, string_msg);
               break;
           default:
               proDialog.dismiss();
               break;

                   }
               }catch (Exception e){
                   e.printStackTrace();
               }

           }

           @Override
           public void onFailure(HttpException e, String s) {
               proDialog.dismiss();
//               Toast toast = Toast.makeText(activity.getApplicationContext(),
//                       "保存失败", Toast.LENGTH_SHORT);
//               toast.setGravity(Gravity.CENTER, 0, 0);
//               LinearLayout toastView = (LinearLayout) toast.getView();
//               ImageView imageCodeProject = new ImageView(activity.getApplicationContext());
//               imageCodeProject.setImageResource(R.drawable.error);
//               toastView.addView(imageCodeProject, 0);
//               toast.show();
               ToastView_custom toast = new ToastView_custom(activity);
               toast.showCustom(activity, "保存失败");

           }
       });




    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }
}
